package kr.hkit.powerjava.chapter26.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

import kr.hkit.powerjava.chapter26.dao.EmployeeDAO;
import kr.hkit.powerjava.chapter26.dto.Employee;

public class EmployeeService extends AbsService<Employee> {
	private ArrayList<Employee> list;

	public EmployeeService(Scanner sc, Connection connection) {
		super(sc, connection);
		dao = new EmployeeDAO(connection);
	}

	@Override
	public Employee inputItemInfo(boolean gubun) {
		System.out.println("사원번호 사원명");
		Employee emp = new Employee(sc.nextInt(), sc.next().trim());
		
		if (gubun) {
			System.out.print("부서번호");
			int dno = sc.nextInt();
			emp.setDno(dno);
		}
		return emp;
	}

	@Override
	public void prnSubMenu() {
		System.out.print("1. 이름순 정렬 2. 위치별 정렬 3. 번호순 정렬");
		try {
			list = dao.listItems();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		int res = sc.nextInt();
		switch(res){
			case 1:
				prnItemList(new Comparator<Employee>() {
					@Override
					public int compare(Employee o1, Employee o2) {
						return o1.getEmpName().hashCode()-o2.getEmpName().hashCode();
					}
				});
				break;
			case 2:
				prnItemList(new Comparator<Employee>() {
					@Override
					public int compare(Employee o1, Employee o2) {
						return o1.getDno()-o2.getDno();
					}
				});
				break;
			default:
				prnItemList(null);
		}
	}

	private void prnItemList(Comparator<Employee> comparator) {
		if (comparator == null){
			Collections.sort(list);
		}else{
			Collections.sort(list, comparator);
		}
		prnlist(list);
	}

	private void prnlist(ArrayList<Employee> list) {
		for(Employee e:list){
			System.out.println(e);
		}
	}

}
